<!-- src/components/Header/AppHeader.vue -->
<template>
  <div id="header" style="display:flex; flex-direction: row;">
    <!-- 左侧 Logo -->
    <div style="width: 40%;">
      <div id="logo"><img src="../../assets/logo.jpg" alt=""></div>
    </div>

    <!-- 右侧导航和头像 -->
    <div style="width: 60%; display: flex; flex-direction: row; justify-content: flex-end; margin-right: 5%;">
      <div class="headerinfo"><a href="#">帮助中心</a></div>
      <div class="headerinfo"><a href="../ShoppingCart">购物车</a></div>
      <div class="headerinfo"><a href="#">收藏夹</a></div>
      <div class="headerinfo"><a href="#">个人资料</a></div>
      <div class="headerinfo"><a href="/">退出登录</a></div>

      <!-- 头像下拉菜单 -->
      <el-dropdown trigger="click">
        <span class="avatar-container">
          <el-avatar
            :size="70"
            :src="avatarUrl || defaultAvatar"
            @error="handleAvatarError"
          />
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item disabled>
              用户名：{{ userInfo.name || '未知' }}
            </el-dropdown-item>
            <el-dropdown-item disabled>
              手机号：{{ userInfo.phone || '未知' }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '@/api/api'

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

// 响应式数据
const avatarUrl = ref('')
const userInfo = ref({
  name: '',
  phone: ''
})

// 加载失败回退默认头像
const handleAvatarError = () => {
  avatarUrl.value = defaultAvatar
}

// 请求用户信息接口（注意：接口应为 /user/info）
const fetchUserInfo = async () => {
  try {
    const res = await api.get('/user/info')
    const data = res.data
    avatarUrl.value = data.avatarUrl || defaultAvatar
    userInfo.value.name = data.name || ''
    userInfo.value.phone = data.phone || ''
  } catch (err) {
    console.error('获取用户信息失败:', err)
    avatarUrl.value = defaultAvatar
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
#header {
  height: 100px;
  background-color: rgb(255, 174, 0);
}

.headerinfo {
  margin-right: 5%;
  height: 100px;
  line-height: 100px;
  font-size: 20px;
}

.headerinfo a {
  text-decoration: none;
  color: #333;
}

.avatar-container {
  display: flex;
  align-items: center;
  margin-left: 20px;
  cursor: pointer;
}
</style>
